<!--
 * @Author: Christion.Young
 * @Date: 2020-11-04 19:42:25
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2020-12-25 17:28:27
 * @Description: 汇率管理
-->
<template>
    <div>
        <el-row>
            <el-col :span="6"
                    style="padding-top:10px;padding:0 10px">
                <!-- <upper-template
          noSearchButton
          :configIcon="false"
          style="height:42px;"
          search-place="left"
        >
          <div slot="buttonArea" class="top-title">
            <span class="vertical-bar"></span>
            币种
          </div>
          <div slot="searchArea">
            <onlyOneSearch
              v-model="filterText"
              placeholder="请输入名称"
              :search-method="filterTree"
            ></onlyOneSearch>
          </div>
        </upper-template> -->
                <vp-tree :vp-header="{
            show: true,
            text: '币种',
            search: true,
            name: 'currencyName'
          }"
                         vp-title="所有币种"
                         :data="treeData"
                         :props="defaultProps"
                         @node-click="handleNodeClick"
                          show-checkbox
                         @check ="handleNodeClick"
                         default-expand-all
                         check-strictly
                         ref="configTree"
                         node-key="currencyId"
                         :expand-on-click-node="false"
                         check-on-click-node></vp-tree>
            </el-col>
            <el-col :span="18">
                <upper-template @search="queryBtn"
                                @clear="resetBtn">
                    <!-- 操作按钮区 -->
                    <template slot="buttonArea">
                        <el-button @click="addFunc">新增</el-button>
                        <el-button @click="editFunc">编辑</el-button>
                        <el-button @click="delFunc">删除</el-button>
                    </template>
                    <!-- 搜索区 -->
                    <template slot="searchArea">
                        <el-form :model="searchForm"
                                 ref="searchForm"
                                 label-width="90px"
                                 label-position="left"
                                 size="mini">
                            <el-form-item label="目标币种：">
                                <el-select v-model="searchForm.dimCurrencyCode"
                                           placeholder="请选择目标币种"
                                           style="width:100%">
                                    <el-option v-for="item in currencyOptionList"
                                               :key="item.currencyCode"
                                               :label="item.currencyName"
                                               :value="item.currencyCode"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="生效日期：">
                                <el-date-picker v-model="searchForm.effDt"
                                                type="date"
                                                style="width:100%;"
                                                value-format="yyyy-MM-dd"
                                                placeholder="请选择生效日期"
                                                format="yyyy-MM-dd"></el-date-picker>
                            </el-form-item>
                        </el-form>
                    </template>
                    <!-- 显示隐藏区 -->
                    <template slot="columnHide">
                        <el-checkbox-group v-model="checkList">
                            <el-checkbox v-for="item in textData"
                                         :label="item.label"
                                         :key="item.prop">{{ item.label }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </template>
                </upper-template>

                <!-- 列表 -->
                <el-table ref="multipleTable"
                          :data="tableData"
                          stripe
                          @row-click="authorizeFor">
                    <el-table-column width="55"
                                     type="selection"
                                     ></el-table-column>
                    <el-table-column prop="dimCurrencyCode"
                                     label="目标币种"
                                     v-if="columnState[0]"
                                     :formatter="
              r =>
                $getLabel(
                  r.dimCurrencyCode,
                  currencyOptionList,
                  'currencyCode',
                  'currencyName'
                )
            ">
                    </el-table-column>
                    <el-table-column prop="exchangeRate"
                                     label="汇率"
                                     v-if="columnState[1]"
                                     :formatter="numChangeType">
                    </el-table-column>
                    <el-table-column prop="effDt"
                                     label="生效日期"
                                     :formatter="row => (row.effDt ? setCalendarDates(row.effDt) : '-')"
                                     v-if="columnState[2]">
                    </el-table-column>
                    <el-table-column prop="creator"
                                     label="创建人"
                                     :formatter="row => row.creator || '-'"
                                     v-if="columnState[3]">
                    </el-table-column>
                    <el-table-column prop="createdTm"
                                     label="创建时间"
                                     :formatter="
              row => (row.createdTm ? setCalendarDate(row.createdTm) : '-')
            "
                                     v-if="columnState[4]">
                    </el-table-column>
                    <el-table-column prop="modifier"
                                     label="修改人"
                                     :formatter="row => row.modifier || '-'"
                                     v-if="columnState[5]">
                    </el-table-column>
                    <el-table-column prop="modifiedTm"
                                     label="修改时间"
                                     :formatter="
              row => (row.modifiedTm ? setCalendarDate(row.modifiedTm) : '-')
            "
                                     v-if="columnState[6]">
                    </el-table-column>
                </el-table>
                 <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @refresh="searchFunc"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          :total="total"
        ></pagination>
            </el-col>
        </el-row>
        <!-- 新增/编辑 -->
        <el-dialog v-dialogDrag
                   :title="saveTitles[saveFlg - 1] + '汇率管理表信息'"
                   :visible.sync="addOrEdit"
                   width="560px"
                   top="5%">
            <el-form :model="saveForm"
                     ref="addTreeForm"
                     label-width="100px"
                     label-position="right"
                     :rules="saveFormRules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="目标币种："
                                      prop="dimCurrencyCode">
                            <el-select v-model="saveForm.dimCurrencyCode"
                                       style="width:400px;">
                                <el-option v-for="item in currencyOptionList"
                                           :key="item.currencyCode"
                                           :label="item.currencyName"
                                           :value="item.currencyCode"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="汇率："
                                      prop="exchangeRate">
                            <el-input v-model="saveForm.exchangeRate"
                                      style="width:400px;"></el-input>
                        </el-form-item>
                        <el-form-item label="生效日期："
                                      prop="effDt">
                            <el-date-picker v-model="saveForm.effDt"
                                            type="date"
                                            style="width:400px;"
                                            value-format="yyyy-MM-dd"
                                            format="yyyy-MM-dd"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer">
                <el-button @click="confirmTne">确 定</el-button>
                <el-button @click="cancelTne">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listToTree } from '@/lib/util'
import { publicManage_dat } from '@/api/index'
import moment from 'moment'

export default {
    data() {
        return {
            filterText: '',
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'currencyName',
            },
            // ===========================================================================================
            addOrEdit: false,
            saveFlg: 1,
            saveTitles: ['新增', '编辑'],
            searchForm: {
                effDt: '',
                dimCurrencyCode: '',
                origCcyCd: '',
                page:1,
                size:15
            },
            total:1,
            saveForm: {
                dimCurrencyCode: '',
                effDt: '',
                exchangeRate: '',
                origCcyCd: '',
                rateId: '',
            },
            saveFormRules: {
                dimCurrencyCode: [
                    {
                        required: true,
                        message: '该输入项为必输项',
                        trigger: 'blur',
                    },
                ],
                exchangeRate: [
                    {
                        required: true,
                        message: '该输入项为必输项',
                        trigger: 'blur',
                    },
                    {
                        pattern: /^(\-)?\d+(\.\d{1,8})?$/,
                        message: '只能输入数值,小数部分最多八位',
                        trigger: 'blur',
                    },
                    {
                        validator: (r, v, c) => {
                            if (v && v > 100000000) {
                                c(new Error('最大值99999999.99999999'))
                            } else if (v && v < 0) {
                                c(new Error('最小值0'))
                            } else {
                                c()
                            }
                        },
                        trigger: 'blur',
                    },
                ],
                effDt: [
                    {
                        required: true,
                        message: '该输入项为必输项',
                        trigger: 'blur',
                    },
                ],
            },
            checkList: [
                '目标币种',
                '汇率',
                '生效日期',
                '创建人',
                '创建时间',
                '修改人',
                '修改时间',
            ],
            textData: [
                { prop: 'currencyName', label: '目标币种' },
                { prop: 'exchangeRate', label: '汇率' },
                { prop: 'effDt', label: '生效日期' },
                { prop: 'dimCurrencyCode', label: '创建人' },
                { prop: 'createdTm', label: '创建时间' },
                { prop: 'modifier', label: '修改人' },
                { prop: 'modifiedTm', label: '修改时间' },
            ],
            tableData: [],
            currencyOptionList: [],
            origCcyCd: '',
        }
    },
    created() {
        this.getMgrOrganTree()
        this.queryAWOutDefault()
    },
    computed: {
        columnState() {
            let arr = [],
                arr1 = this.textData,
                arr2 = this.checkList
            for (let i = 0; i < arr1.length; i++) {
                let flg = false
                for (let j = 0; j < arr2.length; j++) {
                    if (arr1[i].label === arr2[j]) {
                        flg = true
                    }
                }
                arr.push(flg)
            }
            return arr
        },
    },
    mounted() {},
    watch: {
        addOrEdit() {
            // 窗口打开或关闭清除校验结果
            if (this.$refs.addTreeForm) {
                this.$refs.addTreeForm.clearValidate()
            }
        },
    },
    methods: {
        filterTree() {
            this.$refs.configTree.filter(this.filterText)
        },
        filterNode(value, data) {
            if (!value) return true
            return data.currencyName.indexOf(value) !== -1
        },
        // 获取树
        getMgrOrganTree() {
            publicManage_dat.queryAllCurrecyWithOutDefault().then((res) => {
                this.treeData = listToTree('currencyCode', '', res)
                this.$nextTick(() => {
                    this.handleNodeClick(this.treeData[0])
                })
            })
        },
        handleNodeClick(obj) {
      this.$refs.configTree.$tree.setCheckedNodes([]);
      this.$refs.configTree.$tree.setCheckedNodes([obj]);
            this.searchForm.origCcyCd = obj.currencyCode
            this.origCcyCd = obj.currencyCode
            this.searchFunc()
        },
        // ===========================================================================================
        addFunc() {
            this.saveFlg = 1
            for (let k in this.saveForm) {
                this.saveForm[k] = ''
            }
            this.saveForm.origCcyCd = this.origCcyCd
            this.addOrEdit = true
        },
        editFunc() {
            this.saveFlg = 2
            let selection = this.$refs.multipleTable.selection
            if (selection.length != 1) {
                return this.$message.warning('请选择一条数据进行修改')
            }
            let row = selection[0]
            let form = { ...row }
            this.saveForm = form
            this.saveForm.origCcyCd = this.origCcyCd
            this.saveForm.exchangeRate = this.toNonExponential(
                form.exchangeRate
            )
            this.addOrEdit = true
        },
        delFunc() {
            let selection = this.$refs.multipleTable.selection
            if (selection.length < 1) {
                return this.$message.warning('请选择要删除的数据')
            }
            this.$confirm('您确定要删除选中数据吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    const paramData = []
                    selection.forEach((element) => {
                        paramData.push(element.rateId)
                    })
                    publicManage_dat
                        .exchangeRateRemove({ ids: paramData })
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功',
                                })
                                this.searchFunc()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },
        //搜索操作按钮
        queryBtn() {
            this.searchForm.page=1;
            this.searchFunc()
        },
        resetBtn() {
            this.searchForm.effDt = ''
            this.searchForm.dimCurrencyCode = ''
        },
        //新增编辑确定取消
        confirmTne() {
            this.$refs.addTreeForm.validate((valid) => {
                if (valid) {
                    publicManage_dat
                        .exchangeRateSave(this.saveForm)
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '保存成功',
                                })
                                this.searchFunc()
                                this.addOrEdit = false
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                }
            })
        },
        cancelTne() {
            this.addOrEdit = false
        },
        //点击行选中
        authorizeFor(row) {
            if (this.$refs.multipleTable) {
                this.$refs.multipleTable.clearSelection()
            }
            this.$refs.multipleTable.toggleRowSelection(row, true)
        },

        //查询
        searchFunc() {
            publicManage_dat
                .exchangeRateQueryForPage(this.searchForm)
                .then((res) => {
                    if (res.code == 200) {
                        this.tableData = res.data
                        this.total = res.count
                    } else {
                        this.$message.error(res.message)
                    }
                })
        },
        //币种
        queryAWOutDefault() {
            publicManage_dat.queryAllCurrecyWithOutDefault().then((res) => {
                this.currencyOptionList = res
            })
        },
        //日期数据处理
        setCalendarDate(val) {
            if (val) return moment(val).format('YYYY-MM-DD HH:mm:ss')
            else return ''
        },
         setCalendarDates(val) {
            if (val) return moment(val).format('YYYY-MM-DD')
            else return ''
        },
        // 科学计数法格式转换
        numChangeType(row) {
            let num = row.exchangeRate
            return this.toNonExponential(num)
        },
        toNonExponential(num) {
            var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/)
            return num.toFixed(Math.max(0, (m[1] || '').length - m[2]))
        },
          handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc();
    },
    },
}
</script>
<style lang="scss" scoped>
.top-title {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #000000;
    line-height: 20px;
    vertical-align: middle;
    margin-top: 9px;
}
.vertical-bar {
    line-height: 20px;
    font-weight: 500px;
}
</style>